package com.lt.lumentracks.utils;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class IpUtils {

    @Autowired
    private RestTemplate restTemplate;
    private static final String BAIDU_IP_API = "https://opendata.baidu.com/api.php?query=%s&resource_id=6006&oe=utf-8";

    // 常见代理服务器使用的请求头，按优先级排序
    private static final String[] HEADERS_TO_CHECK = {
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_CLIENT_IP",
            "HTTP_X_FORWARDED_FOR",
            "X-Real-IP" // Nginx代理常用头
    };
    private static final String UNKNOWN = "unknown";
    private static final String LOCAL_IPV4 = "127.0.0.1";
    private static final String LOCAL_IPV6 = "0:0:0:0:0:0:0:1";


    // 获取客户端IP地址
    public String getClientIpAddress(HttpServletRequest request) {
        String ip = null;

        // 按优先级检查各个请求头
        for (String header : HEADERS_TO_CHECK) {
            ip = request.getHeader(header);
            if (isValidIp(ip)) {
                break;
            }
        }

        // 如果所有头都无效，使用远程地址
        if (!isValidIp(ip)) {
            ip = request.getRemoteAddr();
        }

        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        return ip;
    }


    // 解析IP归属地
    public String parseIpAddress(String ip) {
        // 拼接完整的请求URL
        String url = String.format(BAIDU_IP_API, ip);

        try {
            // 发送GET请求并获取响应
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

            // 检查响应状态码是否为200
            if (response.getStatusCode().is2xxSuccessful()) {
                return response.getBody();
            } else {
                return "查询失败，状态码：" + response.getStatusCode();
            }
        } catch (Exception e) {
            return "查询异常：" + e.getMessage();
        }
    }


    // 证IP地址是否有效且非unknown
    private static boolean isValidIp(String ip) {
        return ip != null &&
               !ip.isEmpty() &&
               !UNKNOWN.equalsIgnoreCase(ip);
    }

}